//
//  HJCategroyController.m
//  Sneakers
//
//  Created by 胡光健 on 2017/9/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HJCategroyController.h"
#import "HJCategroyNavBar.h"
#import "HJCategroyHeader.h"
#import "HJCategroyCell.h"
#import "HJComprehensiveRankController.h"
#import "HJScreeningViewController.h"
#import "HJSearchController.h"
#import "HJHomeDetailController.h"
#import "HJCategpryModel.h"

@interface HJCategroyController ()<categgroyNavBarDelegate> {
    UIButton *_commodityListBtn;//商品列表
    UIButton *_collectionListBtn;//我的收藏
    UIView *_line;
    NSLayoutConstraint *_lineW;
    NSMutableArray <HJCategpryModel *> * _listArr;
    NSMutableArray <HJCategpryModel *> * _collectShoesArr;
    NSInteger _sort;
    NSString * _brand_id;
    HJCategroyNavBar * _navBar;
    UIButton *_currentbtn;
}
@property(nonatomic,strong)HJCategroyHeader * headerView;
@property (nonatomic, assign) NSInteger page;
@property(nonatomic,assign)BOOL hideHeader;
@property(nonatomic,strong) NSNumber *years;// 年份
@property(nonatomic,assign) NSInteger min_price;// 最大价格
@property(nonatomic,assign) NSInteger max_price;// 最少价格
@property(nonatomic,assign) NSInteger have_goods;// 有无货
@end

@implementation HJCategroyController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
     [self.navigationController setNavigationBarHidden:YES];    
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

-(HJCategroyHeader *)headerView {
    if (!_headerView) {
        _headerView = [[HJCategroyHeader alloc]init];
        _headerView.frame = CGRectMake(0, 0, mScreenWidth, 100);
    }
    return _headerView;
}

-(void)buttonWithIndex:(NSNotification *)not {
    NSInteger index = [not.userInfo[@"index"] integerValue];
    _brand_id = not.userInfo[@"brand_id"];
    CGFloat offsetX = index * 90;
    if (offsetX <= mScreenWidth/2) {
        [_headerView.headerBtns setContentOffset:CGPointMake(0, 0) animated:YES];
    }else if ((_headerView.headerBtns.contentSize.width - offsetX - 90) < mScreenWidth/ 2) {
        [_headerView.headerBtns setContentOffset:CGPointMake(_headerView.headerBtns.contentSize.width - mScreenWidth, 0) animated:YES];
    }else {
        UIView *view = [_headerView.headerBtns viewWithTag:index];
        CGPoint point = [_headerView convertPoint:view.center fromView:_headerView.headerBtns];
        CGFloat inspace = _headerView.headerBtns.contentOffset.x + point.x - mScreenWidth / 2.0;
        [_headerView.headerBtns setContentOffset:CGPointMake(inspace, 0) animated:YES];
    }
    [_listArr removeAllObjects];
    [[NSUserDefaults standardUserDefaults] setObject:@(0) forKey:@"row"];
    [[NSUserDefaults standardUserDefaults] setObject:@(0) forKey:@"have_goods"];
    [[NSUserDefaults standardUserDefaults] setObject:@(0) forKey:@"years"];
    [[NSUserDefaults standardUserDefaults] setObject:@(0.0) forKey:@"min"];
    [[NSUserDefaults standardUserDefaults] setObject:@(1.0) forKey:@"max"];
    [[NSUserDefaults standardUserDefaults] setObject:@"￥0~￥5000+" forKey:@"priceNotext"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    _headerView.rightLabel.text = @"筛选";
    _headerView.leftLabel.text = @"综合排序";
    self.min_price = 0;
    self.max_price = 0;
    self.have_goods = 0;
    _sort = 0;
    self.years = @0;
    self.page = 1;
    [self loadWork];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [mNotificationCenter addObserver:self selector:@selector(screeningListBtnPush:) name:@"screeningListBtnPush" object:nil];
    [mNotificationCenter addObserver:self selector:@selector(synthesizeBtnPush:) name:@"synthesizeBtnPush" object:nil];
    [mNotificationCenter addObserver:self selector:@selector(buttonWithIndex:) name:@"buttonWithIndex" object:nil];
    [mNotificationCenter addObserver:self selector:@selector(collectionBtn:) name:@"collectionNotification" object:nil];
    [mNotificationCenter addObserver:self selector:@selector(outLoginNotification) name:@"outLoginNotification" object:nil];
    [self configNavigation];
    _hideHeader = YES;
    _listArr = [NSMutableArray array];
    [self loadNetworkData];
    [self loadWork];
    _collectShoesArr =[NSMutableArray array];
    [self loadCollectShoesData];
    
    [self Refresh];
}

-(void)configNavigation {
    _navBar = [[HJCategroyNavBar alloc]init];
    _navBar.frame = CGRectMake(0, 0, mScreenWidth, 144);
    _navBar.delegate = self;
    [self.view addSubview:_navBar];
}

-(void)categroyNavBarWithAllBtn:(UIButton *)btn {
    if (btn.tag==11) {
        _hideHeader = NO;
        _navBar.line.hidden = YES;
        _navBar.line2.hidden = NO;
        _navBar.collectBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:15];
        _navBar.collectBtn.alpha = 1.0;
        _navBar.listBtn.alpha = 0.5;
        _navBar.listBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
        [self loadCollectShoesData];
    }else {
        _hideHeader = YES;
        _navBar.line.hidden = NO;
        _navBar.line2.hidden = YES;
        _navBar.collectBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
        _navBar.listBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:15];
        _navBar.collectBtn.alpha = 0.5;
        _navBar.listBtn.alpha = 1.0;
        [self loadWork];
    }
}


-(void)categroyNavBarWithSearchBtn:(UIButton *)btn {
    HJSearchController * searchVC = [[HJSearchController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
-(void)collectionBtn:(NSNotification *)not {
//    NSInteger i = [not.userInfo[@"i"] integerValue];
//    [_navBar.collectBtn setTitle:[NSString stringWithFormat:@"我的收藏(%zd)",_collectShoesArr.count +i] forState:UIControlStateNormal];
//    [self loadCollectShoesData];
}
-(void)outLoginNotification {
    [self loadWork];
//    [_navBar.collectBtn setTitle:@"我的收藏(0)" forState:UIControlStateNormal];
    [_collectShoesArr removeAllObjects];
}
-(void)configTableView {
    self.tableViewStyle = UITableViewStylePlain;
    [super configTableView];
    self.tableView.frame = CGRectMake(0, 94, mScreenWidth, mScreenHeight-94-TabBar_H);
//    [self.tableView registerCellByNibName:@"HJCategroyCell"];
}
#pragma mark -- 商品列表
-(void)loadNetworkData {
    [TZHttpTool post:ShoesIndexAPI params:nil success:^(NSDictionary *result) {
        self.totalPage = result[@"data"][@"shoes"][@"totalPage"];
        self.headerView.headerArr = result[@"data"][@"brand"];
        [self.tableView reloadData];
        [self.tableView endRefresh];
    } failure:^(NSString *msg) {
        [self showErrorHUDWithError:msg];
    }];
}
- (void)Refresh {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDataWithHeader)];
    self.tableView.mj_header = header;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshDataWithFooter)];
    self.tableView.mj_footer = footer;
}

- (void)refreshDataWithFooter {
    self.page ++;
    if (self.page > [self.totalPage integerValue]) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self loadWork];
    }
}

- (void)refreshDataWithHeader {
    self.page = 1;
    [self loadNetworkData];
    [self loadWork];
}
-(void)loadWork {
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"sort"] = @(_sort);
    params[@"page"] = @(self.page);
    params[@"min_price"] = @(self.min_price);
    params[@"max_price"] = @(self.max_price);
    params[@"years"] = self.years;
    params[@"have_goods"] = @(self.have_goods);
    params[@"brand_id"] = _brand_id;
    [TZHttpTool post:ShoesIndexAPI params:params success:^(NSDictionary *result) {
        NSArray *arr = [HJCategpryModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"shoes"][@"models"]];
        if (self.page==1) {
            [_listArr removeAllObjects];
        }
        self.totalPage = result[@"data"][@"shoes"][@"totalPage"];
        [_listArr addObjectsFromArray:arr];
        [self.tableView reloadData];
        [self.tableView endRefresh];
    } failure:^(NSString *msg) {
        [self showErrorHUDWithError:msg];
    }];
}
#pragma mark -- 收藏列表
-(void)loadCollectShoesData {
    [TZHttpTool post:CollectIndexAPI params:nil success:^(NSDictionary *result) {
        NSArray * arr = [HJCategpryModel mj_objectArrayWithKeyValuesArray:result[@"data"]];
        [_collectShoesArr removeAllObjects];
        [_collectShoesArr addObjectsFromArray:arr];
        [self.tableView reloadData];
        [self.tableView endRefresh];
    } failure:^(NSString *msg) {
        [self showErrorHUDWithError:msg];
    }];
}
-(NSInteger)listNoData {
    if (_listArr.count>0) {
        [self.tableView hideNoData];
        return _listArr.count;
    }
    [self.tableView showNoData]; return 0;
}

-(NSInteger)collectShoesNoData {
    if (_collectShoesArr.count>0) {
        [self.tableView hideNoData];
        return _collectShoesArr.count;
    }
    [self.tableView showNoData]; return 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _hideHeader ? [self listNoData] : [self collectShoesNoData];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCategroyCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"HJCategroyCell" owner:nil options:nil].firstObject;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_hideHeader) {
        if (_listArr.count>0) {
            cell.model = _listArr[indexPath.row];
        }
    }else {
        cell.model = _collectShoesArr[indexPath.row];
    }
    cell.collectBool = _hideHeader;
    cell.collectionBtnBlock = ^(BOOL collectBool) {
        [_collectShoesArr removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
    };
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 156;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return _hideHeader ? 100 : 0.001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return _hideHeader ? self.headerView : nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJHomeDetailController *homeDetailVC = [[HJHomeDetailController alloc]init];
    if (_hideHeader) {
        HJCategpryModel *model = _listArr[indexPath.row];
        homeDetailVC.shoes_id = model.shoes_id;
    }else {
        HJCategpryModel *model = _collectShoesArr[indexPath.row];
        homeDetailVC.shoes_id = model.shoes_id;
    }
    [self.navigationController pushViewController:homeDetailVC animated:YES];
}

-(void)synthesizeBtnPush:(NSNotification*)not {
    HJComprehensiveRankController * comprehensiveVC = [[HJComprehensiveRankController alloc]init];
    WeakSelf
    comprehensiveVC.bock = ^(NSInteger sort, NSString * btnTitle) {
        _sort = sort;
        _headerView.leftLabel.text = btnTitle;
        [weakSelf loadWork];
    };
    HJNavigationViewController * nav = [[HJNavigationViewController alloc]initWithRootViewController:comprehensiveVC];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)screeningListBtnPush:(NSNotification *)not {
    HJScreeningViewController *screenVC = [[HJScreeningViewController alloc]init];
    WeakSelf
    screenVC.block = ^(NSInteger have_goods, NSInteger max_price, NSInteger min_price, NSNumber *years, NSNumber *right_btn) {
        if ([right_btn isEqual:@1]) {
            weakSelf.min_price = 0;
            weakSelf.max_price = 0;
            weakSelf.have_goods = 0;
            _sort = 0;
            weakSelf.years = @0;
            weakSelf.page = 1;
            _headerView.rightLabel.text = @"筛选";
            _headerView.leftLabel.text = @"综合排序";
        }else {
            weakSelf.have_goods = have_goods;
            weakSelf.max_price = max_price;
            weakSelf.min_price = min_price;
            weakSelf.years = years;
            _headerView.rightLabel.text = [NSString stringWithFormat:@"￥%ld~%ld/%@",(long)min_price,(long)max_price,years];
        }
        [weakSelf loadWork];
    };
    HJNavigationViewController * nav = [[HJNavigationViewController alloc]initWithRootViewController:screenVC];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

@end
